package com.zts.base.exception;

import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.text.MessageFormat;
import java.util.UUID;

/**
 * Created by Zhangkh on 2017/5/31.
 */
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class CommonException extends RuntimeException {

    private static final String DEFAULT_CODE = CommonExceptionCode.UNKNOWN_ERROR;

    private String id = UUID.randomUUID().toString();

    private String code = DEFAULT_CODE;

    private static String format(String pattern, Object[] args) {
        if (StringUtils.isEmpty(pattern)) {
            return DEFAULT_CODE;
        }

        if (args == null || args.length == 0) {
            return pattern;
        }

        StringBuilder sb = new StringBuilder();

        int index = 0;
        for(String part : pattern.split("\\{ *\\}", -1)) {
            if (index != 0) {
                sb.append("{");
                sb.append(index - 1);
                sb.append("}");
            }
            sb.append(part);
            ++index;
        }

        return MessageFormat.format(sb.toString(), args);
    }

    protected CommonException() {
        super(DEFAULT_CODE);
    }

    public CommonException(String message, Object... args) {
        super(format(message, args));
    }
    protected CommonException(Throwable cause) {
        super(DEFAULT_CODE, cause);
    }

    protected CommonException(Throwable cause, String message, Object... args) {
        super(format(message, args), cause);
    }

    protected CommonException(MessageSource messageSource, String code, Object... args) {
        super(messageSource.getMessage(code, args, null));
        this.code = code;
    }

    protected CommonException(Throwable cause, MessageSource messageSource, String code, Object... args) {
        super(messageSource.getMessage(code, args, null), cause);
        this.code = code;
    }

    public String getCode() {
        return code;
    }

    public String getId() {
        return id;
    }

    protected void setCode(String code) {
        this.code = code;
    }
}
